/**
 * 多端存储工具
 */
import platform from './platform.js'
import constant from './constant'

// 存储变量名
let storageKey = 'storage_data'

// 存储节点变量名
let storageNodeKeys = [constant.avatar, constant.id, constant.name, constant.roles, constant.permissions]

// 存储数据
export const setStorage = (key, data) => {
  return new Promise((resolve, reject) => {
    try {
      // #ifdef H5
      // H5环境使用localStorage
      if (typeof data === 'object') {
        localStorage.setItem(key, JSON.stringify(data))
      } else {
        localStorage.setItem(key, data)
      }
      resolve()
      // #endif

      // #ifdef MP-WEIXIN || APP-PLUS
      // 小程序和APP使用uni.setStorage
      uni.setStorage({
        key: key,
        data: data,
        success: resolve,
        fail: reject
      })
      // #endif
    } catch (error) {
      reject(error)
    }
  })
}

// 同步存储数据
export const setStorageSync = (key, data) => {
  try {
    // #ifdef H5
    if (typeof data === 'object') {
      localStorage.setItem(key, JSON.stringify(data))
    } else {
      localStorage.setItem(key, data)
    }
    // #endif

    // #ifdef MP-WEIXIN || APP-PLUS
    uni.setStorageSync(key, data)
    // #endif

    return true
  } catch (error) {
    console.error('存储失败:', error)
    return false
  }
}

// 获取存储数据
export const getStorage = (key) => {
  return new Promise((resolve, reject) => {
    try {
      // #ifdef H5
      const data = localStorage.getItem(key)
      if (data === null) {
        reject(new Error('数据不存在'))
        return
      }

      try {
        resolve(JSON.parse(data))
      } catch (e) {
        resolve(data)
      }
      // #endif

      // #ifdef MP-WEIXIN || APP-PLUS
      uni.getStorage({
        key: key,
        success: (res) => resolve(res.data),
        fail: reject
      })
      // #endif
    } catch (error) {
      reject(error)
    }
  })
}

// 同步获取存储数据
export const getStorageSync = (key) => {
  try {
    // #ifdef H5
    const data = localStorage.getItem(key)
    if (data === null) return null

    try {
      return JSON.parse(data)
    } catch (e) {
      return data
    }
    // #endif

    // #ifdef MP-WEIXIN || APP-PLUS
    return uni.getStorageSync(key)
    // #endif
  } catch (error) {
    console.error('获取存储失败:', error)
    return null
  }
}

// 删除存储数据
export const removeStorage = (key) => {
  return new Promise((resolve, reject) => {
    try {
      // #ifdef H5
      localStorage.removeItem(key)
      resolve()
      // #endif

      // #ifdef MP-WEIXIN || APP-PLUS
      uni.removeStorage({
        key: key,
        success: resolve,
        fail: reject
      })
      // #endif
    } catch (error) {
      reject(error)
    }
  })
}

// 同步删除存储数据
export const removeStorageSync = (key) => {
  try {
    // #ifdef H5
    localStorage.removeItem(key)
    // #endif

    // #ifdef MP-WEIXIN || APP-PLUS
    uni.removeStorageSync(key)
    // #endif

    return true
  } catch (error) {
    console.error('删除存储失败:', error)
    return false
  }
}

// 清空所有存储
export const clearStorage = () => {
  return new Promise((resolve, reject) => {
    try {
      // #ifdef H5
      localStorage.clear()
      resolve()
      // #endif

      // #ifdef MP-WEIXIN || APP-PLUS
      uni.clearStorage({
        success: resolve,
        fail: reject
      })
      // #endif
    } catch (error) {
      reject(error)
    }
  })
}

// 获取存储信息
export const getStorageInfo = () => {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    let keys = []
    let currentSize = 0

    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i)
      keys.push(key)
      currentSize += localStorage.getItem(key).length
    }

    resolve({
      keys: keys,
      currentSize: currentSize,
      limitSize: 5 * 1024 * 1024 // 5MB限制
    })
    // #endif

    // #ifdef MP-WEIXIN || APP-PLUS
    uni.getStorageInfo({
      success: resolve,
      fail: reject
    })
    // #endif
  })
}

// 用户相关存储
export const userStorage = {
  // 保存用户信息
  setUserInfo: (userInfo) => {
    return setStorage('userInfo', userInfo)
  },

  // 获取用户信息
  getUserInfo: () => {
    return getStorageSync('userInfo')
  },

  // 保存token
  setToken: (token) => {
    return setStorageSync('token', token)
  },

  // 获取token
  getToken: () => {
    return getStorageSync('token')
  },

  // 清除用户数据
  clearUserData: () => {
    removeStorageSync('token')
    removeStorageSync('userInfo')
    removeStorageSync('loginTime')
  },

  // 保存登录时间
  setLoginTime: () => {
    return setStorageSync('loginTime', Date.now())
  },

  // 检查登录是否过期
  isLoginExpired: () => {
    const loginTime = getStorageSync('loginTime')
    if (!loginTime) return true

    const expireTime = 7 * 24 * 60 * 60 * 1000 // 7天
    return Date.now() - loginTime > expireTime
  }
}

// 应用设置存储
export const settingsStorage = {
  // 保存应用设置
  setSettings: (settings) => {
    return setStorage('appSettings', settings)
  },

  // 获取应用设置
  getSettings: () => {
    return getStorageSync('appSettings') || {
      theme: 'light',
      fontSize: 'medium',
      autoPlay: true,
      pushNotification: true
    }
  },

  // 更新单个设置
  updateSetting: (key, value) => {
    const settings = settingsStorage.getSettings()
    settings[key] = value
    return setStorageSync('appSettings', settings)
  }
}

// 缓存管理
export const cacheStorage = {
  // 设置缓存（带过期时间）
  setCache: (key, data, expireTime = 30 * 60 * 1000) => {
    const cacheData = {
      data: data,
      timestamp: Date.now(),
      expireTime: expireTime
    }
    return setStorageSync(`cache_${key}`, cacheData)
  },

  // 获取缓存
  getCache: (key) => {
    const cacheData = getStorageSync(`cache_${key}`)
    if (!cacheData) return null

    const now = Date.now()
    if (now - cacheData.timestamp > cacheData.expireTime) {
      // 缓存过期，删除
      removeStorageSync(`cache_${key}`)
      return null
    }

    return cacheData.data
  },

  // 清除过期缓存
  clearExpiredCache: () => {
    return getStorageInfo().then(info => {
      const expiredKeys = []
      const now = Date.now()

      info.keys.forEach(key => {
        if (key.startsWith('cache_')) {
          const cacheData = getStorageSync(key)
          if (cacheData && now - cacheData.timestamp > cacheData.expireTime) {
            expiredKeys.push(key)
          }
        }
      })

      expiredKeys.forEach(key => {
        removeStorageSync(key)
      })

      return expiredKeys.length
    })
  }
}

// 历史记录存储
export const historyStorage = {
  // 添加搜索历史
  addSearchHistory: (keyword) => {
    if (!keyword || keyword.trim() === '') return

    let history = getStorageSync('searchHistory') || []

    // 移除重复项
    history = history.filter(item => item !== keyword)

    // 添加到开头
    history.unshift(keyword)

    // 限制数量
    if (history.length > 20) {
      history = history.slice(0, 20)
    }

    return setStorageSync('searchHistory', history)
  },

  // 获取搜索历史
  getSearchHistory: () => {
    return getStorageSync('searchHistory') || []
  },

  // 清除搜索历史
  clearSearchHistory: () => {
    return removeStorageSync('searchHistory')
  },

  // 添加浏览历史
  addBrowseHistory: (item) => {
    let history = getStorageSync('browseHistory') || []

    // 移除重复项
    history = history.filter(h => h.id !== item.id || h.type !== item.type)

    // 添加到开头
    history.unshift({
      ...item,
      timestamp: Date.now()
    })

    // 限制数量
    if (history.length > 100) {
      history = history.slice(0, 100)
    }

    return setStorageSync('browseHistory', history)
  },

  // 获取浏览历史
  getBrowseHistory: () => {
    return getStorageSync('browseHistory') || []
  }
}

export default {
  setStorage,
  setStorageSync,
  getStorage,
  getStorageSync,
  removeStorage,
  removeStorageSync,
  clearStorage,
  getStorageInfo,
  userStorage,
  settingsStorage,
  cacheStorage,
  historyStorage
}
